package cn.tedu.controller;

import cn.tedu.pojo.Car;
import cn.tedu.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@RestController
@RequestMapping("car")
public class CarController {
    @Autowired
    private CarService carService;
    @RequestMapping("get")
    public Car get(){
        return carService.get();
    }
    @RequestMapping("add")
    public Car add(Car c) throws Exception {
            carService.add(c);
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://localhost:3307/py-school-db?characterEncoding=utf8";
            Connection conn = DriverManager.getConnection(url,"root","123456");
            String sql = "insert into car values(?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, c.getName());
            ps.setString(2,c.getColor());
            ps.setDouble(3,c.getPrice());
            ps.executeLargeUpdate();
            ps.close();
            conn.close();
            System.out.println("入库成功");
            return c;
    }
    @RequestMapping("update")
    public Car update(Car c) throws Exception {
        carService.update(c);
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3307/py-school-db?characterEncoding=utf8";
        Connection conn = DriverManager.getConnection(url,"root","123456");
        String sql = "update Car set price=? where name=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setDouble(1,c.getPrice());
        ps.setString(2,c.getName());
        ps.executeLargeUpdate();
        ps.close();
        conn.close();
        System.out.println("更改成功");
        return c;
    }
}
